<template>
    <van-nav-bar title="注册区域" left-text="返回" left-arrow @click-left="() => { $router.push('/') }" fixed />
    <div style="height: 45px;"></div>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="username" name="username" label="用户名" placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                立即注册
            </van-button>
        </div>
    </van-form>
    <div style="margin: 16px;">
        <van-button round block type="primary" @click="goregister">
            去登录
        </van-button>
    </div>
</template>

<script setup>
import { ref } from 'vue';
// 引入成功/失败的提示
import { showSuccessToast, showFailToast } from 'vant';
// 引入跳转
import { useRouter } from 'vue-router'
const router = useRouter()
// 自定义绑定数据
let username = ref('');
let password = ref('');
// 获取 登录接口函数
import { registerApi } from '@/api/api'
// 利用 onsubmit  验证、
// 登录 验证
const onSubmit = () => {
    // 先判断 密码的长度
    if (password.value.length > 8) {
        // 提示 并进行清空
        showFailToast('密码长度不能大于8位置');
        password.value = ''
    } else {
        registerApi(username.value, password.value).then(res => {
            console.log('请求数据', res)
            if (res.data.code == 0) {
                // 成功
                showSuccessToast('注册成功');
                // 跳转到的登录   
                router.push('/login')
            } else {
                // 失败
                showFailToast('登录失败');
            }
        })

    }
}
// 点击去注册
const goregister = ()=>{
    router.push('/login')
}
</script>

<style lang="scss" scoped></style>